package com.ds.infra.rpc.core.util;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;

/**
 * 网络工具类
 *
 * @author WeiShaoying
 */
@UtilityClass
@Slf4j
public class NetUtils {

    public static String getLocalHost() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            log.error("Get localhost error", e);
            return "127.0.0.1";
        }
    }

    public static boolean isPortAvailable(int port) {
        try (ServerSocket ignored = new java.net.ServerSocket(port)) {
            return true;
        } catch (Exception e) {
            log.warn("Port {} is in use", port);
            return false;
        }
    }
}
